<template>
  <div class="app-container">
    <!--条件搜索表单-->
    <div style="margin-bottom: -20px">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchObj.name" placeholder="角色名称" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchObj.roleKey" placeholder="角色标识" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchObj.status" placeholder="角色状态" clearable @change="getAll()">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.text" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getAll()">查询</el-button>
          <el-button icon="el-icon-refresh" @click="reset()">清空</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="el-toolbar" style="margin-top: 10px">
      <div class="el-toolbar-body">
        <el-button v-if="hasPerm('sys:role:save')" type="primary" icon="el-icon-plus" @click="openEdit(null)">新增</el-button>
        <el-button v-if="hasPerm('sys:role:batch-delete')" type="danger" icon="el-icon-delete" :disabled="ids.length < 1" @click="batchDelete">
          批量删除
        </el-button>
      </div>
    </div>

    <!-- banner列表 :data="list"表示遍历list数组 stripe条纹 -->
    <el-table
      v-loading="loading"
      element-loading-text="正在努力加载数据中..."
      :data="page.records"
      :border="false"
      highlight-current-row
      stripe
      style="width: 100%; margin: 15px 0px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" fixed="left" width="55" />
      <el-table-column type="index" fixed="left" width="80" label="序号" />
      <el-table-column prop="name" fixed="left" label="角色名称" sortable show-overflow-tooltip />
      <el-table-column prop="roleKey" label="角色标识" show-overflow-tooltip />
      <el-table-column prop="priority" label="优先级" min-width="90" sortable />
      <el-table-column prop="status" label="状态" min-width="100" sortable :filters="statusOptions" :filter-method="filterHandler">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" min-width="100" sortable show-overflow-tooltip />

      <!-- 操作 -->
      <el-table-column
        v-if="hasPerm('sys:role:save-auth', 'sys:role:update', 'sys:role:delete')"
        label="操作"
        width="200"
        fixed="right"
        align="center"
      >
        <template slot-scope="scope">
          <el-link v-if="hasPerm('sys:role:save-auth')" type="primary" icon="el-icon-s-flag" @click="openAuth(scope.row)">授权</el-link>
          <el-divider direction="vertical" />
          <el-link v-if="hasPerm('sys:role:update')" type="success" icon="el-icon-edit" @click="openEdit(scope.row)">编辑</el-link>
          <el-divider direction="vertical" />
          <el-link v-if="hasPerm('sys:role:delete')" type="danger" icon="el-icon-remove" @click="remove(scope.row.id)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页导航栏 -->
    <div>
      <el-pagination
        :background="true"
        :current-page="pIndex"
        :page-size="pSize"
        :total="page.total"
        :page-sizes="[1, 3, 6, 9, 12, 15, 18]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        @current-change="getAll"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 表单 -->
    <el-dialog v-if="hasPerm('sys:role:save', 'sys:role:update')" :title="dialogTitle" :visible.sync="visible" @close="close('roleForm')">
      <el-form ref="roleForm" :model="role" :rules="rules" label-width="80px">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="ID" prop="id" :hidden="true">
              <el-input v-model="role.id" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="角色名称" prop="name" required>
              <el-input v-model="role.name" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="角色标识" prop="roleKey" required>
              <el-input v-model="role.roleKey" placeholder="请输入角色标识" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="role.status" style="width: 100%">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.text" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="优先级" prop="priority">
              <el-input-number v-model="role.priority" controls-position="right" placeholder="请输入优先级" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="role.remark" :rows="3" type="textarea" placeholder="请输入备注" maxlength="255" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close('roleForm')">取 消</el-button>
        <el-button type="primary" @click="save('roleForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 授权 -->
    <el-dialog v-if="hasPerm('sys:role:save-auth')" :title="authFormTitle" :visible.sync="authVisible">
      <div style="margin-bottom: 15px">
        <el-button type="primary" size="small" @click="expandAll(true)">全部展开</el-button>
        <el-button type="primary" size="small" @click="expandAll(false)">全部折叠</el-button>
        <el-button type="primary" size="small" @click="selectAll(true)">全选</el-button>
        <el-button type="primary" size="small" @click="selectAll(false)">全不选</el-button>
        <el-button type="text">
          <el-checkbox label="联选" @change="strictlyCheck = !strictlyCheck" />
        </el-button>
      </div>

      <el-tree
        ref="menuTree"
        style="max-height: calc(60vh - 140px); overflow: auto"
        :data="authData"
        show-checkbox
        :check-strictly="strictlyCheck"
        node-key="id"
        :default-expanded-keys="[1]"
        :props="authProps"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="authVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAuth()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入api接口定义的js文件
import roleApi from '@/api/sys/role'
import menuApi from '@/api/sys/menu'

export default {
  data() {
    // 定义变量和初始值
    return {
      statusOptions: [
        { value: 0, text: '正常' },
        { value: 1, text: '停用' }
      ],
      loading: false,
      pIndex: 1, // 当前页
      pSize: 6, // 每页显示记录数
      searchObj: {}, // 条件封装对象
      page: [], // 列表
      ids: [],
      visible: false,
      userForm: {},
      isEdit: false,
      authVisible: false,
      authData: [],

      // 表单
      dialogTitle: '',
      role: {
        id: undefined,
        name: '',
        roleKey: '',
        status: 0,
        priority: 0,
        remark: ''
      },

      // 验证规则
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        roleKey: [
          { required: true, message: '角色标识不能为空', trigger: 'blur' },
          { pattern: /^[A-Za-z_]+$/, message: '角色标识只能包含字母和下划线', trigger: 'blur' }
        ]
      },

      // 授权
      strictlyCheck: false,
      authProps: {
        children: 'children',
        label: 'menuName'
      },
      authRoleId: undefined,
      menuIds: [],
      authFormTitle: ''
    }
  },
  created() {
    this.getAll()
  },
  methods: {
    // 加载列表数据
    getAll(current = 1) {
      this.loading = true
      this.pIndex = current
      roleApi
        .getPage(this.pIndex, this.pSize, this.searchObj)
        .then((response) => {
          this.page = response.data
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 行内筛选
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },

    // 改变页码
    handleSizeChange(pageSize) {
      this.pSize = pageSize
      // 重新调用数据加载方法 --> 方法中已经加入的查询参数
      this.getAll()
    },

    // 改变状态
    handleStatusChange(row) {
      const text = row.status === 0 ? '正常' : '停用'
      this.$confirm(`此操作将修改 '${row.name}' 状态为 '${text}', 是否继续?`, '角色状态修改', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          roleApi
            .updateStatus(row.id, row.status)
            .then((resp) => {
              this.$message.success('操作成功！')
            })
            .catch(() => {
              row.status = row.status === 0 ? 1 : 0
            })
        })
        .catch(() => {
          row.status = row.status === 0 ? 1 : 0
        })
    },

    // 删除角色信息
    remove(id) {
      this.$confirm('此操作将永久删除角色信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        roleApi.deleteById(id).then((resp) => {
          this.$message.success('删除成功!')
          this.getAll()
        })
      })
    },

    // 复选框选中
    handleSelectionChange(r) {
      // 得到选中的id
      this.ids = r.map((v) => v.id)
    },

    // 打开编辑
    openEdit(row) {
      this.dialogTitle = '新增角色'
      this.visible = true
      this.role.priority = this.page.total + 2

      if (row != null) {
        this.dialogTitle = '编辑角色'
        roleApi.getById(row.id).then((res) => {
          Object.assign(this.role, res.data)
        })
      }
    },

    // 关闭表单
    close(form) {
      this.visible = false
      this.$refs[form].resetFields()
    },

    // 保存
    save(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const apiCall = this.role.id ? roleApi.update(this.role) : roleApi.save(this.role)
          apiCall.then(() => {
            this.$message.success('操作成功')
            this.close(form)
            this.getAll()
          })
        }
      })
    },

    // 获取权限列表
    getAuth() {
      menuApi.getList({}).then((res) => {
        this.authData = res.data
      })
    },

    // 打开授权页面
    async openAuth(row) {
      await this.getAuth()

      this.authRoleId = row.id
      this.authFormTitle = `分配权限-${row.name}`
      // 显示权限弹框
      this.authVisible = true

      // 获取角色权限
      roleApi.getAuth(row.id).then((res) => {
        this.menuIds = res.data
        //  先清空选中状态
        this.$refs['menuTree'].setCheckedKeys([])
        this.menuIds.forEach((i) => {
          // 根据id 拿到 Tree 组件中的node的所有信息
          const node = this.$refs['menuTree'].getNode(i)
          // node.isLeaf：判断当前节点是否为子节点
          if (node.isLeaf) {
            // 如果是子节点，就把状态设置成选中
            this.$refs['menuTree'].setChecked(node, true)
          }
        })
      })
    },

    // 全部展开/折叠
    expandAll(expand) {
      const nodes = this.$refs.menuTree.store.nodesMap
      for (const i in nodes) {
        nodes[i].expanded = expand
      }
    },

    // 全选/全不选
    selectAll(select) {
      if (select) {
        this.seltAllSelect(this.authData)
        this.$refs.menuTree.setCheckedKeys(this.menuIds)
      } else {
        this.$refs.menuTree.setCheckedKeys([])
      }
    },

    // 递归
    seltAllSelect(menuList) {
      menuList.forEach((el) => {
        this.menuIds.push(el.id)
        if (el.children && el.children.length > 0) {
          this.seltAllSelect(el.children)
        }
      })
    },

    // 保存权限
    saveAuth() {
      // 获取选中的子节点
      const checkedKeys = this.$refs['menuTree'].getCheckedKeys()
      // 获取选中的父节点
      const hafCheckedKeys = this.$refs['menuTree'].getHalfCheckedKeys()
      // 合并
      const menuIds = checkedKeys.concat(hafCheckedKeys)

      // 保存
      roleApi.saveAuth({ roleId: this.authRoleId, menuIds: menuIds }).then(() => {
        this.$message.success('操作成功')
        this.authVisible = false
      })
    },

    // 批量删除
    batchDelete() {
      if (this.ids.length > 0) {
        this.$confirm('此操作将永久删除角色信息,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          // 确定执行then方法
          .then(() => {
            roleApi.batchDelete(this.ids).then((resp) => {
              this.$message.success('删除成功!')
              this.getAll()
            })
          })
      } else {
        this.$message.warning('至少选择一条数据!')
      }
    },

    // 重置
    reset() {
      this.searchObj = {}
      this.getAll()
    }
  }
}
</script>
